<?php
declare(strict_types=1);

namespace app\appointment\service;

use app\appointment\model\User as UserModel;
use app\appointment\model\UserOauth as UserOauthModel;
use app\common\service\BaseService;
use app\common\library\wechat\WxBase;
use app\appointment\service\user\Oauth as OauthService;

class Appointment extends BaseService
{
    /**
     * 获取小程序码
     */
    public function getCode($appointmentId, $path)
    {
        // 获取当前小程序信息
        $wxConfig = OauthService::getMpWxConfig();
        // 微信登录 (获取session_key)
        $WxUser = new WxBase($wxConfig['app_id'], $wxConfig['app_secret']);
        $buffer = $WxUser->getCode('appointmentId='.$appointmentId, $path);
        return $buffer;
        // // 将二进制转换成图片文件
        // $path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/temporary/';
        // $file = $this->change_picture($buffer, $path);
        // // 将文件转换成base64格式
        // $base64Image = $this->base64EncodeImage($file);
        // // 删除临时文件
        // $this->delDirAndFile($path);
        // return $base64Image;
    }

    public function change_picture($imgs, $path)
    {
        if (!is_dir($path)) {
            mkdir($path);
        }
        $new_file = $path . time() . '.png'; //生成图片的名字
        if (!empty($imgs)) {
            $file = fopen($new_file, 'w'); //打开文件准备写入
            fwrite($file, $imgs); //写入
            fclose($file); //关闭
        }
        return $new_file;
    }

    function base64EncodeImage($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image =
            'data:' .
            $image_info['mime'] .
            ';base64,' .
            chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    function delDirAndFile($path, $delDir = true)
    {
        if (is_array($path)) {
            foreach ($path as $subPath) {
                $this->delDirAndFile($subPath, $delDir);
            }
        }
        if (is_dir($path)) {
            $handle = opendir($path);
            if ($handle) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != '.' && $item != '..') {
                        is_dir("$path/$item")
                            ? $this->delDirAndFile("$path/$item", $delDir)
                            : unlink("$path/$item");
                    }
                }
                closedir($handle);
                if ($delDir) {
                    return rmdir($path);
                }
            }
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return false;
            }
        }
        clearstatcache();
    }
}
